import java.util.Arrays;
import java.util.PriorityQueue;

public class LC502D {
    public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
        int n=profits.length;
        int[][] arr=new int[n][2];
        for (int i = 0; i < n; i++) {
            arr[i][0]=capital[i];
            arr[i][1]=profits[i];
        }
        Arrays.sort(arr,(a,b)->a[0]-b[0]);
        PriorityQueue<Integer> queue=new PriorityQueue<>((a,b)->b-a);
        int now=0;
        for (int i = 0; i < k; i++) {
            while (now<n && arr[now][0]<=w){
                queue.add(arr[now][1]);
                now++;
            }
            if (queue.isEmpty())break;
            w+=queue.poll();
        }
        return w;
    }
}
